﻿// ChatServer.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <mutex>
#include <thread>
#include "IOcontextPool.h"
#include <boost/asio.hpp>
#include "configMgr.h"
#include "CServer.h"
#include "RedisMgr.h"
#include "ChatServiceImpl.h"
bool b_stop = false;
std::condition_variable cond_var;
std::mutex mtx;
int main()
{
	try {
		auto& config = configMgr::GetInst();
		auto& pool = IOcontextPool::GetInst();
		auto server_name = config["SelfServer"]["Name"];
		RedisMgr::GetInstance().HSet(LOGIN_COUNT, server_name, "0");
		std::string server_address(config["SelfServer"]["Host"] + ":" + config["SelfServer"]["RPCPort"]);
		ChatServiceImpl service;
		grpc::ServerBuilder builder;
		builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
		builder.RegisterService(&service);
		std::unique_ptr<grpc::Server> grpc_server(builder.BuildAndStart());
		std::cout << "RPC Server listening on" << server_address << std::endl;

		std::thread grpc_server_thread([&grpc_server] {
			grpc_server->Wait();
			});
		boost::asio::io_context ioc;
		boost::asio::signal_set signals(ioc, SIGINT, SIGTERM);
		signals.async_wait([&ioc, &pool](auto, auto)
			{
				ioc.stop();
			});
		auto port = config["SelfServer"]["Port"];
		CServer server(ioc, std::stoi(port));
		ioc.run();

		RedisMgr::GetInstance().HDel(LOGIN_COUNT, server_name);
		RedisMgr::GetInstance().Close();
		grpc_server_thread.join();
	}
	catch (std::exception& e)
	{
		std::cerr << "Exception e:" << e.what() << std::endl;
   }
}

